#!/bin/bash

#Optimize Swap
#
#Authors:
#  Bruno Goncalves Araujo <www.biglinux.com.br>
#
#License: GPLv2 or later
#################################################


#Check permission
if test $(id -u) != 0
then
    echo "Need root permission"
    exit 0
fi

function bigcompcache()
{
	cd /usr/share/bigcompcache
	if [ "$(modinfo ramzswap.ko | grep vermagic: | awk '{ print $2 }')" = "$(uname -r)" ]; then
	    ./use_ramzswap.sh $1
	else
	    make clean
	    make
	    ./use_ramzswap.sh $1
	fi
}


#Options
case "$1" in

    start)
        if [ "$(grep MemTotal: /proc/meminfo | awk '{print $2}')" -le "300000" ]
        then
            echo 80 > /proc/sys/vm/swappiness
	    bigcompcache $[$(grep MemTotal: /proc/meminfo | awk '{print $2}') / 2]
	    exit 0
        fi

        if [ "$(grep MemTotal: /proc/meminfo | awk '{print $2}')" -le "600000" ]
        then
            echo 60 > /proc/sys/vm/swappiness
	    bigcompcache $[$(grep MemTotal: /proc/meminfo | awk '{print $2}') / 2]
	    exit 0
        fi

        if [ "$(grep MemTotal: /proc/meminfo | awk '{print $2}')" -le "1000000" ]
        then
            echo 45 > /proc/sys/vm/swappiness
	    bigcompcache $[$(grep MemTotal: /proc/meminfo | awk '{print $2}') / 3]
	    exit 0
        fi

        if [ "$(grep MemTotal: /proc/meminfo | awk '{print $2}')" -le "2000000" ]
        then
            echo 25 > /proc/sys/vm/swappiness
	    bigcompcache $[$(grep MemTotal: /proc/meminfo | awk '{print $2}') / 4]
	    exit 0
        fi

        if [ "$(grep MemTotal: /proc/meminfo | awk '{print $2}')" -le "3000000" ]
        then
            echo 10 > /proc/sys/vm/swappiness
	    exit 0
        fi
    ;;

    stop)
	cd /usr/share/bigcompcache
	./unuse_ramzswap.sh
	exit 0
    ;;

    *)
        echo "Optimize cache and RAM with swappiness and compcache

start
stop
"

    ;;

esac

